<template>
  <div class="login-container">
    <el-form :model="registerForm" status-icon :rules="rules" ref="registerForm" label-width="80px" class="registerForm">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="registerForm.name" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="registerForm.password" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('registerForm')">注册</el-button>
      </el-form-item>
      <router-link to="/login" class="link">去登录</router-link>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'register',
  data() {
    return {
      registerForm: {
        name: '',
        email: '',
        password: '',
      },
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post('/api/users/register', this.registerForm)
          console.log(res)
          if (res.status === 1) return this.$message.error(res.message)
          this.$router.push('/login')
          this.$message.success(res.message)
        } else {
          this.$message.error('表单验证不通过')
          return false
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.login-container {
  height: 100%;
  padding-top: 200px;
  background-color: rgba(0, 0, 0, 0.7);
  .registerForm {
    width: 500px;
    height: 400px;
    padding-top: 50px;
    padding-right: 50px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 10px;
    .el-button {
      margin: 20px 0 0 140px;
    }
    .link {
      margin-left: 230px;
    }
  }
}
</style>
